package com.monas.server.transfer;

import java.io.BufferedWriter;
import java.io.FileWriter;

import com.monas.server.MonasConstants;
import com.monas.server.MonasException;
import com.monas.server.MonasHelper;
import com.monas.server.MonasProperties;

/**
 * 
 * @author ekowahyudi
 * 
 */
public class MonasTransferClient implements MonasConstants {

	private SSHClient sshClient = null;

	private String os = null;

	private String serverName;
	private String folder;

	public MonasTransferClient(String serverName) throws MonasException {

		this.serverName = serverName;
		folder = MonasProperties.getDBProperty(DB_TRANSFER_DIR);

		/**
		 * Get profile server from Database. Like user name, host, password,
		 * transfer time, and other configuration.
		 */
		os = MonasProperties.getDBProperty(serverName, DB_OS);
		String user = MonasProperties.getDBProperty(serverName, DB_USER);
		String password = MonasProperties.getDBProperty(serverName, DB_PASSWD);
		String host = MonasProperties.getDBProperty(serverName, DB_HOST);
		String endLine = MonasProperties.getDBProperty(serverName, DB_ENDLINE);

		try {
			sshClient = new SSHClient(host, user, password, endLine);
		} catch (Exception e) {
			throw new MonasException("Error access into " + serverName);
		}

	}

	private void createFile(String name, String contain) throws MonasException {
		String fileName = folder + "/" + serverName + "_" + name + "_"
				+ MonasHelper.getTimeName() + ".txt";
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(fileName));
			writer.write(contain);
			writer.flush();
		} catch (Exception e) {
			throw new MonasException("Cannot create file " + fileName
					+ " because " + e.getMessage());
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (Exception e2) {
				}
			}
		}
	}

	public void getFiles() throws MonasException {

		try {
			if (os.equalsIgnoreCase("solaris")) {
				// TODO: Set for operating system Solaris.
			} else {
				sshClient.sendCommand("free -m");
				createFile("freem", sshClient.readUntil());

				sshClient.sendCommand("top -n 1 | grep Cpu");
				createFile("cpu", sshClient.readUntil());
			}

			sshClient.sendCommand("df -h");
			createFile("dfh", sshClient.readUntil());
		} catch (Exception e) {
			throw new MonasException("Failure sending command from "
					+ serverName + " because " + e.getMessage());
		}
	}

	public void disconnect() {
		if (sshClient != null) {
			try {
				sshClient.disconnect();
			} catch (Exception e) {
				System.out.println("Failure disconnecting from " + serverName);
			}
		}
	}

}
